#!/usr/bin/env bash

set -euo pipefail


source "$(dirname -- $BASH_SOURCE)/../tools/unix/find-python3.sh"
PYTHON_PATH=$(get_python3)
if [[ -z "$PYTHON_PATH" ]]; then
  echo
  echo "python3 is required for formatting and was not found"
  echo
  echo "ERROR: you must either install python3 and try pushing again or run `git push` with `--no-verify`"
  exit 1
fi

while read LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA
do
  git fetch origin main &>/dev/null
  # Check all local changes, not present in origin/main, for lint.
  set +e
  $PYTHON_PATH "$(dirname -- $BASH_SOURCE)/../tools/cross/format.py" --check git --source $LOCAL_SHA --target origin/main
  EXIT_CODE=$?
  set -e
  case $EXIT_CODE in
    0)
      # No lint.
      ;;
    1)
      echo
      echo "ERROR: changes in $LOCAL_REF have lint which may fail CI."
      echo
      echo "To fix lint:"
      echo "  just format"
      echo
      exit 1
      ;;
    2)
      echo
      echo "ERROR: failed to run format.py, Pass '--no-verify' or '-n' to skip."
      echo
      exit 1
      ;;
  esac
done
